package com.epam.facebook_client.services;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.text.TextUtils;

import com.epam.facebook_client.processor.MethodFactory;
import com.epam.facebook_client.processor.ProcessorFactory;
import common.processor.IProcessor;

public class RESTService extends IntentService {
	public static final String EXTRA_STATUS_RECEIVER = "receiver";
	public static final String TAG = RESTService.class.getSimpleName();
	private static final int POOL_SIZE = 2;

	private ExecutorService executorService;

	public RESTService() {
		super(TAG);
		executorService = Executors.newFixedThreadPool(POOL_SIZE);
	}

	@Override
	protected void onHandleIntent(final Intent intent) {
		final String action = intent.getAction();
		final String method = intent.getStringExtra(IProcessor.EXTRA_EXECUTE_METHOD);
		if (!TextUtils.isEmpty(action)) {
			final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_STATUS_RECEIVER);
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					IProcessor processor = ProcessorFactory.getInstance().getProcessor(action);
					Bundle resultData = null;
					try {
						resultData = MethodFactory.getInstance().execute(method, processor, intent);
						receiver.send(IProcessor.RESULT_OK, resultData);
					} catch (Exception e) {
						Bundle dataError = new Bundle();
						dataError.putSerializable(IProcessor.EXTRAS_ERROR, e);
						receiver.send(IProcessor.RESULT_ERROR, dataError);
					}
				}
			});

		}
	}

}
